import asyncio
import aiohttp

# requests.get() 同步的代码 ——> 异步操作aiohttp(模块)

urls = [
    'http://kr.shanghai-jiuxin.com/file/2022/0414/9e5827678bd12db0999a573254e40d1e.jpg',
    'http://kr.shanghai-jiuxin.com/file/2022/0414/33f06e321d65146414aefd830013dfe7.jpg',
    'http://kr.shanghai-jiuxin.com/file/2022/0414/718c092b7239a6c185c2a0fc3167bef8.jpg'
]

async def aiodownload(url):
    name = url.rsplit('/',1)[1]  # 从右边开始切
    # s = aiohttp.ClientSession()  # 等价于requests模块
    async with aiohttp.ClientSession() as session:
        # 发送请求
        async with session.get(url) as res:  # 加了with 执行这一步会帮你自动关闭 不用再close了
            # 请求回来了 写入文件
            with open(r'D:\ui\reptile\coroutines\data\%s'%name,'wb') as f:
                f.write(await res.content.read())   # 异步操作读取加await
            #res.content.read()   # ===> 等价于res.content

            # res.text()  # 读 text
            # res.json()  # 读json

    print(name,'over!')
    # 得到图片内容
    # 保存到文件

async def main():
    tasks = []
    for url in urls:
        tasks.append(asyncio.create_task(aiodownload(url)))

    await asyncio.wait(tasks)

if __name__ == '__main__':
    # asyncio.run(main())
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())


